import { Middleware } from 'koa';

const errorHandle: Middleware = async (ctx, next) => {
  try {
    await next();
  } catch (err: any) {
    // some errors will have .status
    // however this is not a guarantee
    ctx.status = err.status || 500;
    if (ctx.accepts('application/json') === 'application/json') {
      ctx.body = {
        code: err.code || ctx.status,
        message: err.message,
      };
    } else {
      ctx.type = 'html';
      ctx.body = '<p>Something <em>exploded</em>, please contact Maru.</p>';
    }

    if (['ValidateError', 'AuthorizedError'].indexOf(err.name) === -1) {
      ctx.app.emit('error', err, ctx);
    }
  }
};
export default errorHandle;
